package com.sky.com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.ThreadLocalUtil;
import com.sky.dto.EmployeeDTO;

import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.BusinessException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;


    // 员工登录
    @Override
    public Employee login(EmployeeDTO employeeDTO) {
        String username = employeeDTO.getUsername();
        String password = employeeDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            throw new BusinessException(2200, "非法参数");
        }
        //2. 根据用户名查询数据库
        Employee employee = employeeMapper.getByUsername(username);
        //3.业务校验
        // 3-1 用户是否存在
        if (employee == null) {
            throw new BusinessException(200, "用户名不存在");
        }
        // 3-2 密码是否正确
        String md5 = SecureUtil.md5(password);
        if (!StrUtil.equals(md5, employee.getPassword())) {
            throw new BusinessException(200, "密码错误");
        }
        //3-3 账号是否被禁用
        if (employee.getStatus() == StatusConstant.DISABLE) {
            throw new BusinessException(200, "此账号被禁用，请联系管理员");
        }
        //4. 登录成功，返回employee
        return employee;
    }


    @Override
    public Employee getById(Long id) {
        return employeeMapper.getById(id);
    }

    /**
     * 根据ID修改员工信息
     *
     * @param employeeDTO
     **/
    @Override
    public void update(EmployeeDTO employeeDTO) {
        //1. 非法参数校验
        if(employeeDTO == null){
            throw new BusinessException(200,"修改id不能为空");
        }
        //2. 加一个校验手机号

        // 3. dto->entity
        Employee employee = BeanUtil.copyProperties(employeeDTO, Employee.class);
        // 3-1 补充信息
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(ThreadLocalUtil.getCurrentId());

        //4 调用mapper修改
        employeeMapper.update(employee);

    }

    //修改时业务校验
    private void updateBusinessCheck(EmployeeDTO employeeDTO) {
        String username = employeeDTO.getUsername();
        String phone = employeeDTO.getPhone();
        String idNumber = employeeDTO.getIdNumber();

        Employee employee = employeeMapper.getByUsername(username);
        if (employee != null && !employee.getId().equals(employeeDTO.getId())) {
            throw new BusinessException(400, "账号已存在");
        }
        employee = employeeMapper.getByPhone(phone);
        if (employee != null && !employee.getId().equals(employeeDTO.getId())) {
            throw new BusinessException(400, "手机号已存在");
        }
        employee = employeeMapper.getIdNumber(idNumber);
        if (employee != null && !employee.getId().equals(employeeDTO.getId())) {
            throw new BusinessException(400, "证件号已存在");
        }

    }


    /**
     * 账号启用禁用
     *
     * @param status
     * @param id
     **/
    @Override
    public void startOrStop(Integer status, Long id) {
        Employee employee = Employee.builder()
                .id(id)
                .status(status).build();
        //2. 补充信息
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(ThreadLocalUtil.getCurrentId());
        //3. 调用mapper修改
        employeeMapper.updateById(employee);
    }


    // 员工分页
    @Override
    public PageResult getPage(EmployeePageQueryDTO employeePageQueryDTO) {
        // 1.开启分页
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        //2.查询List
        List<Employee> list = employeeMapper.getList(employeePageQueryDTO.getName());
        Page<Employee> page = (Page<Employee>) list;
        //3. 返回
        return new PageResult(page.getTotal(), page.getResult());


    }

    // 新增员工
    @Override
    public void save(EmployeeDTO employeDTO) {
        //1. 参数校验
        if (
                StrUtil.isBlank(employeDTO.getUsername()) ||
                StrUtil.isBlank(employeDTO.getName()) ||
                        StrUtil.isBlank(employeDTO.getPhone()) ||
                        StrUtil.isBlank(employeDTO.getIdNumber())
        ) {
            throw new BusinessException(200,"表单填写不完整,请确认");
        }
        //2.业务校验
        // 2-1 账号唯一
        Employee byUsername = employeeMapper.getByUsername(employeDTO.getUsername());
        if(byUsername != null){
            throw new BusinessException(200,"此账号已存在");
        }
        // 2-2 手机号唯一
        Employee byPhone = employeeMapper.getByPhone(employeDTO.getPhone());
        if(byPhone != null){
            throw new BusinessException(200,"此手机号已存在");
        }
        // 2-3 身份证号唯一
        Employee idNumber = employeeMapper.getIdNumber(employeDTO.getIdNumber());
        if(idNumber != null){
            throw new BusinessException(200,"此身份证号已存在");
        }
        //3. dto->entity
        Employee employee = BeanUtil.copyProperties(employeDTO, Employee.class);
        //3-1 补全信息
        String md5 = SecureUtil.md5(PasswordConstant.DEFAULT_PASSWORD);
        employee.setPassword(md5);
        employee.setStatus(StatusConstant.ENABLE);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser(ThreadLocalUtil.getCurrentId());
        employee.setUpdateUser(ThreadLocalUtil.getCurrentId());
        //4.调用mapper保存到数据库
        employeeMapper.insert(employee);
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     **/
    @Override
    public void add(EmployeeDTO employeeDTO) {
        //参数校验-非空
        //username name phone idNumber
        emParamsCheck(employeeDTO);
        //业务校验
        empBusinessCheck(employeeDTO);
        //完成业务-添加员工(写操作要看表）
        //补全数据-DTO 转PO
        Employee empPO = empDTO2PO(employeeDTO);
        employeeMapper.insert(empPO);
    }

    /**
     * 员工分页查询
     *
     * @param name
     * @param page
     * @param pageSize
     **/
    @Override
    public PageResult page(String name, Integer page, Integer pageSize) {
        //1. 开启分页
        PageHelper.startPage(page, pageSize);
        //2.查询
        List<Employee> list = employeeMapper.listLikeName(name);
        //3. 封装分页结果
        PageInfo<Employee> pageInfo = new PageInfo<>(list);
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    //补全数据-DTO 转PO
    private Employee empDTO2PO(EmployeeDTO employeeDTO) {
        Employee empPO = BeanUtil.copyProperties(employeeDTO, Employee.class);
        empPO.setPassword(SecureUtil.md5("123456"));
        empPO.setCreateTime(LocalDateTime.now());
        empPO.setUpdateTime(LocalDateTime.now());
        empPO.setCreateUser(ThreadLocalUtil.getCurrentId());
        empPO.setUpdateUser(ThreadLocalUtil.getCurrentId());
        System.out.println("[Service]当前线程名称: " + Thread.currentThread().getName());
        return empPO;
    }

    //业务校验
    private void empBusinessCheck(EmployeeDTO employeeDTO) {
        Employee employee = employeeMapper.getByUsername(employeeDTO.getUsername());
        if (employee != null) {
            throw new BusinessException(400, "账号已被注册");
        }
        employee = employeeMapper.getByPhone(employeeDTO.getPhone());
        if (employee != null) {
            throw new BusinessException(400, "手机号已被注册");
        }
        employee = employeeMapper.getIdNumber(employee.getIdNumber());
        if (employee != null) {
            throw new BusinessException(400, "身份证号已被注册");
        }

    }

    //参数校验
    private void emParamsCheck(EmployeeDTO employeeDTO) {
        String username = employeeDTO.getUsername();
        String name = employeeDTO.getName();
        String phone = employeeDTO.getPhone();
        String idNumber = employeeDTO.getIdNumber();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(name) || StrUtil.isBlank(phone) || StrUtil.isBlank(idNumber)) {
            throw new BusinessException(400, "表单填写不完整，请确认");
        }


    }
}